<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:report:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:report:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="sn" />
      <el-table-column label="报损时间" align="center" prop="reportTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reportTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门名称" align="center" prop="deptName" />
      <el-table-column label="调整说明" align="center" prop="reportDesc" />
      <el-table-column label="报损类型" align="center" prop="damageTypeValue" />
      <el-table-column label="制单人" align="center" prop="creator" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0">未提交</span>
          <span v-else-if="scope.row.status === 1">待审核</span>
          <span v-else-if="scope.row.status === 2">审核通过</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 提交按钮，仅当状态为“0”时显示 -->
          <el-button
            v-if="scope.row.status === 0"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleSubmit(scope.row)"
            v-hasPermi="['system:inventory:audit']"
          >提交</el-button>
          <el-button
            v-if="scope.row.status === 1"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAudit(scope.row)"
            v-hasPermi="['system:inventory:audit']"
          >审核</el-button>
          <el-button
            v-if="scope.row.status === 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:report:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:report:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 商品选择对话框 -->
    <el-dialog title="选择报损商品" :visible.sync="productDialogVisible" width="80%">
      <el-form :inline="true" :model="productQueryParams" size="small">
        <el-form-item label="仓库：">
          <el-select v-model="productQueryParams.warehouseId" placeholder="请选择仓库">
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="productQueryParams.keyword"
            placeholder="请输入商品名称或编号"
            clearable
            @keyup.enter.native="handleProductSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleProductSearch">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="productList"
        @selection-change="handleProductSelectionChange"
        border
        style="width: 100%">

        <el-table-column type="selection" width="55" align="center" />

        <el-table-column prop="stockSn" label="入库编号" align="center" />
        <el-table-column prop="product_sn" label="商品编号" align="center" />
        <el-table-column prop="product_name" label="商品名称" align="center" />
        <el-table-column prop="specification" label="规格型号" align="center" />
        <el-table-column prop="unit" label="单位" align="center" />
        <el-table-column prop="stock_num" label="库存数量" align="center" />

        <el-table-column label="明细类型" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.detail_type" size="small">
              <el-option label="销售活动" value="销售活动" />
              <el-option label="库存消耗" value="库存消耗" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="明细数量" align="center">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.detail_num"
              :min="0"
              :max="scope.row.stock_num"
              controls-position="right"
              size="small" />
          </template>
        </el-table-column>

        <el-table-column label="明细说明" align="center">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.detail_desc"
              placeholder="请输入说明"
              size="small" />
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="productDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmProductSelection">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改库存报损单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 编号 -->
        <el-form-item label="编号" prop="sn">
          <el-input
            v-model="form.sn"
            placeholder="请输入编号"
            :disabled="form.isAdd"
            class="form-uniform-width"
          />
        </el-form-item>

        <!-- 部门名称 -->
        <el-form-item label="部门名称" prop="deptId">
          <el-select
            v-model="form.deptId"
            placeholder="请选择部门名称"
            clearable
            class="form-uniform-width"
          >
            <el-option
              v-for="dept in deptOptions"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>

        <!-- 仓库名称 -->
        <el-form-item label="仓库名称" prop="warehouseId">
          <el-select
            v-model="form.warehouseId"
            placeholder="请选择仓库名称"
            clearable
            class="form-uniform-width"
          >
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>

        <!-- 制单人 -->
        <el-form-item label="制单人">
          <el-cascader
            v-model="form.creatorId"
            :options="personList"
            :props="{ checkStrictly: true, value: 'id', label: 'realName' }"
            placeholder="请选择制单人"
            class="form-uniform-width"
            @change="handleCreatorChange"
          />
        </el-form-item>

        <!-- 报损时间 -->
        <el-form-item label="报损时间" prop="reportTime">
          <el-date-picker
            v-model="form.reportTime"
            type="date"
            placeholder="请选择报损时间"
            value-format="yyyy-MM-dd"
            class="form-uniform-width"
          />
        </el-form-item>

        <!-- 报损类型 -->
        <el-form-item label="报损类型" prop="damageTypeValue">
          <el-select
            v-model="form.damageTypeValue"
            placeholder="请选择报损类型"
            clearable
            class="form-uniform-width"
          >
            <el-option
              v-for="item in damageTypeKey"
              :key="item.key"
              :label="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 调整说明 -->
        <el-form-item label="调整说明" prop="reportDesc">
          <el-input
            v-model="form.reportDesc"
            placeholder="请输入调整说明"
            class="form-uniform-width"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="showProductDialog">选择报损商品</el-button>
        </el-form-item>

        <el-table :data="form.products" border style="width: 100%">
          <el-table-column prop="productSn" label="商品编号" align="center" />
          <el-table-column prop="productName" label="商品名称" align="center" />
          <el-table-column prop="specification" label="规格型号" align="center" />
          <el-table-column prop="unit" label="单位" align="center" />
          <el-table-column prop="stockNum" label="库存数量" align="center" />
          <el-table-column prop="reportNum" label="报损数量" align="center" />
          <el-table-column prop="reportRemark" label="备注" align="center" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="removeProduct(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listReport,
  getReport,
  delReport,
  addReport,
  updateReport,
  submitReport,
  auditReport, getDamageTypes, listGoodsWithStock
} from '@/api/system/report'
import { listDept } from "@/api/erpsystem/dept";
import { listWarehouse } from "@/api/system/warehouse";
import {
  getCompiler,
} from "@/api/procurementmanagement/plan";


export default {
  name: "Report",
  data() {
    return {
      productDialogVisible: false,
      productQueryParams: {
        warehouseId: null,
        keyword: ''
      },
      productList: [],
      selectedProducts: [],
      personList:[],
      damageTypeKey: [ // 报损类型列表
        { key: '销售活动', value: '销售活动' },
        { key: '库存消耗', value: '库存消耗' }
      ],
      // 部门选项
      deptOptions: [],
      // 仓库选项
      warehouseOptions: [],
      //用户选项
      userOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存报损单表格数据
      reportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
        deptId: null,
        deptName: null,
        warehouseId: null,
        warehouseName: null,
        creatorId: null,
        creator: null,
        reportTime: null,
        damageTypeKey: null,
        damageTypeValue: null,
        reportDesc: null,
        status: null,
        rejectReason: null,
        auditTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDeptOptions();
    this.getWarehouseOptions();
    this.getUserOptions();
  },
  methods: {
    // 显示商品选择对话框
    showProductDialog() {
      if (!this.form.warehouseId) {
        this.$message.warning('请先选择仓库');
        return;
      }
      this.productQueryParams.warehouseId = this.form.warehouseId;
      this.productDialogVisible = true;
      this.getProductList();
    },

    // 搜索商品
    handleProductSearch() {
      this.getProductList();
    },

    // 获取商品列表
    getProductList() {
      listGoodsWithStock({
        warehouseId: this.productQueryParams.warehouseId,
        keyword: this.productQueryParams.keyword
      }).then(response => {
        this.productList = response.rows.map(item => {
          return {
            ...item,
            reportNum: 0,
            reportRemark: '',
            detail_num: 0 // 初始化报损数量
          };
        });
        console.log("商品列表数据：", this.productList); // 调试用
      });
    },

    // 处理商品选择变化
    handleProductSelectionChange(selection) {
      this.selectedProducts = selection;
    },

    // 确认选择商品
    confirmProductSelection() {
      if (!this.form.products) {
        this.form.products = [];
      }
      this.selectedProducts.forEach(product => {
        this.form.products.push({
          stockSn: product.stock_sn,
          productId: product.product_id,
          productSn: product.product_sn,
          productName: product.product_name,
          specification: product.specification,
          unit: product.unit,
          stockNum: product.stock_num,
          reportNum: product.detail_num || 0,  // 确保有默认值
          reportRemark: product.detail_desc || ''
        });
        console.log(JSON.stringify(product), "0")

      });
      this.productDialogVisible = false;
    },

    // 移除商品
    removeProduct(index) {
      this.form.products.splice(index, 1);
    },
    /** 提交按钮操作 */
    handleSubmit(row) {
      const id = row.id;
      this.$modal.confirm('是否确认提交库存报损单编号为"' + id + '"的数据项？').then(() => {
        return submitReport(id);
      }).then(() => {
        this.$modal.msgSuccess("提交成功");
        this.getList(); // 刷新列表
      }).catch(() => {});
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      const id = row.id;
      this.$modal.confirm('是否确认审核通过库存报损单编号为"' + id + '"的数据项？').then(() => {
        return auditReport(id);
      }).then(() => {
        this.$modal.msgSuccess("审核通过");
        this.getList(); // 刷新列表
      }).catch(() => {});
    },
    /** 查询库存报损单列表 */
    getList() {
      this.loading = true;
      listReport(this.queryParams).then(response => {
        console.log(response);
        this.reportList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 获取部门列表 */
    getDeptOptions() {
      listDept().then(response => {
        response.data.forEach(dept => {
          dept.deptName = dept.name;
        });
        this.deptOptions = response.data;
      });
    },
    /** 获取仓库列表 */
    getWarehouseOptions() {
      listWarehouse().then(response => {
        response.rows.forEach(warehouse => {
          warehouse.warehouseName = warehouse.name;
        });
        this.warehouseOptions = response.rows;
      });
    },
    /** 获取用户列表 */
    getUserOptions() {
      listErpuser().then(response => {
        this.userOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        deptId: null,
        deptName: null,
        warehouseId: null,
        warehouseName: null,
        creatorId: null,
        creator: null,
        reportTime: null,
        damageTypeValue: null,
        reportDesc: null,
        createTime: null,
        status: null,
        rejectReason: null,
        auditTime: null,
        isAdd: false
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.form.isAdd = true; // 设置新增标识
      this.form.sn = this.generateRandomSn(); // 生成随机编号
      this.getCompiler(); // 获取编制人
      this.open = true;
      this.title = "添加库存报损单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getReport(id).then(response => {
        this.form = response.data;
        this.getCompiler(); // 获取编制人
        this.form.isAdd = false; // 设置为修改操作
        this.open = true;
        this.title = "修改库存报损单";
      });
    },
    //获取编制人
    getCompiler(){
      getCompiler().then(response => {
        this.personList = response.data;
      })
    },
    handleCreatorChange(value) {
      if (value.length > 0) {
        // 获取选中项的最后一个值作为 id
        const selectedPerson = this.personList.find(person => person.id.toString() === value[value.length - 1].toString());
        if (selectedPerson) {
          this.form.creatorId = selectedPerson.id; // 保存编制人 ID 到表单
          this.form.creator = selectedPerson.realName; // 保存编制人名称到表单
        }
      } else {
        this.form.creatorId = null;
        this.form.creator = null;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.planList = this.planList;
          if (this.form.id != null) {
            updateReport(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.form.isAdd) {
              this.form.sn = this.generateRandomSn(); // 提交时重新生成随机编号
            }
            addReport(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除库存报损单编号为"' + ids + '"的数据项？').then(function() {
        return delReport(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/report/export', {
        ...this.queryParams
      }, `report_${new Date().getTime()}.xlsx`)
    },
    generateRandomSn() {
      const prefix = "BS"; // 随机编号前缀
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
      return `${prefix}${year}${month}${day}${randomNum}`; // 拼接前缀和随机编号
    },
  }
};
</script>

<style scoped>
/* 统一表单元素宽度 */
.form-uniform-width {
  width: 100% !important;
}

/* 调整表单标签样式 */
.el-form-item__label {
  width: 100px;
  text-align: right;
  padding-right: 12px;
}

/* 调整级联选择器下拉菜单宽度 */
.el-cascader-menu {
  min-width: 100%;
}

/* 调整日期选择器样式 */
.el-date-editor.el-input {
  width: 100%;
}

/* 确保表单内容区域对齐 */
.el-form-item__content {
  margin-left: 100px;
}

/* 调整文本域高度 */
.el-textarea__inner {
  min-height: 80px;
  resize: vertical;
}

/* 下拉菜单最小宽度 */
.el-select-dropdown {
  min-width: 100% !important;
}

/* 操作按钮样式 */
.dialog-footer {
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
}
</style>
